/**
 * @(#)com.framework.web.wechat.controller.WeChatGoodsController
 *
 * Copyright (c) 2014-2018 一抹风光
 *
 * DESC:
 *
 */
package com.framework.web.wechat.controller;

import com.framework.core.domain.SessionVo;
import com.framework.core.util.*;
import com.framework.web.bus.domain.*;
import com.framework.web.bus.service.DeliveryAreaService;
import com.framework.web.bus.service.ExpressService;
import com.framework.web.bus.service.OrderService;
import com.framework.web.bus.service.UserAddressService;
import com.framework.web.common.domain.BusinessConstants;
import com.framework.web.common.domain.Constants;
import com.framework.web.sys.domain.User;
import com.framework.web.sys.service.UserService;
import com.framework.web.wechat.domain.*;
import com.framework.web.wechat.util.ExpressUtil;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.awt.SunHints;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

/**
 * 用户相关功能
 *
 * @author fusf
 * @version 1.0  2016/9/11
 */
@Controller
@RequestMapping("/weChat/user")
public class WeChatUserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserAddressService userAddressService;


    @Autowired
    private DeliveryAreaService deliveryAreaService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ExpressService expressService;

    /**
     * 14.	获取个人信息
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getInfo", method = RequestMethod.GET)
    @ResponseBody
    public Object getInfo(WeChatRequest requestInfo, HttpServletRequest request) throws Exception {
        WeChatResInfo resInfo = new WeChatResInfo();
        //根据userGuid 找到userId
        ServletContext application = request.getSession().getServletContext();
        if (application.getAttribute(requestInfo.getUserGuid()) == null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", BusinessConstants.WECHAT_STATUS.E50010003);
            map.put("msg", "登陆权限已经过期");
            resInfo.setResult(map);
            return resInfo;
        }
        SessionVo sessionVo = (SessionVo) application.getAttribute(requestInfo.getUserGuid());
        User user = userService.findById(sessionVo.getUserId());
        if (user == null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", BusinessConstants.WECHAT_STATUS.E50010003);
            map.put("msg", "用户信息不存在");
            resInfo.setResult(map);
            return resInfo;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userGuid", requestInfo.getUserGuid());
        map.put("nickName", user.getNickName());//昵称
        map.put("phone", user.getUserName());//电话
        map.put("integral", user.getIntegration());//积分
        map.put("inviteCode", user.getInviteCode());//邀请码
        map.put("email", user.getEmail());//邮箱
        map.put("photo", user.getImage());//头像
        map.put("sex", UserUtil.getSex(user.getSex()));//性别
        map.put("access_token", user.getAccessToken());//access_token
        map.put("openid", user.getOpenId());//openid
        map.put("subscribe", user.getSubscribe());//关注状态
        map.put("language", user.getLanguage());//语言
        map.put("city", user.getCity());//城市
        map.put("province", user.getProvince());//省份
        map.put("country", user.getCountry());//国家
        map.put("headimgurl", user.getHeadImgUrl());//头像图片路径
        map.put("subscribe_time", DateUtils.formateDate(user.getSubscribeTime()));//关注时间

        map.put("status", BusinessConstants.WECHAT_STATUS.SUCCESS);
        map.put("msg", "成功");
        resInfo.setResult(map);
        return resInfo;

    }

    /**
     * 修改个人信息
     *
     * @param requestInfo
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/setInfo", method = RequestMethod.GET)
    @ResponseBody
    public Object updateUser(WeChatRequest requestInfo, HttpServletRequest request) throws Exception {
        WeChatResInfo resInfo = new WeChatResInfo();
        //根据userGuid 找到userId
        ServletContext application = request.getSession().getServletContext();
        if (application.getAttribute(requestInfo.getUserGuid()) == null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", BusinessConstants.WECHAT_STATUS.E50010003);
            map.put("msg", "登陆权限已经过期");
            resInfo.setResult(map);
            return resInfo;
        }
        SessionVo sessionVo = (SessionVo) application.getAttribute(requestInfo.getUserGuid());
        User user = userService.findById(sessionVo.getUserId());
        if (user == null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", BusinessConstants.WECHAT_STATUS.E50010003);
            map.put("msg", "用户信息不存在");
            resInfo.setResult(map);
            return resInfo;
        }
        String nickName = requestInfo.getNickName();//昵称
        String phone = requestInfo.getPhone();//手机号码
        String inviteCode = requestInfo.getInviteCode();//邀请码
        String email = requestInfo.getEmail();//email
        String sex = requestInfo.getSex();//性别
        if (StringUtil.isNotEmpty(nickName)) {
            user.setNickName(nickName);
        }
        if (StringUtil.isNotEmpty(phone)) {
            user.setUserName(phone);
        }
        if (StringUtil.isNotEmpty(inviteCode)) {
            user.setInviteCode(inviteCode);
        }
        if (StringUtil.isNotEmpty(email)) {
            user.setEmail(email);
        }
        if (StringUtil.isNotEmpty(sex)) {
            user.setSex(sex);
        }
        userService.save(user);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", BusinessConstants.WECHAT_STATUS.SUCCESS);
        map.put("msg", "成功");
        resInfo.setResult(map);
        return resInfo;

    }

    /**
     * 收货地址列表
     *
     * @param requestInfo
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/receiptAddress", method = RequestMethod.GET)
    @ResponseBody
    public Object receiptAddress(WeChatRequest requestInfo, HttpServletRequest request) throws Exception {
        WeChatResInfo resInfo = new WeChatResInfo();

        //根据userGuid 找到userId
        ServletContext application = request.getSession().getServletContext();
        if (requestInfo.getUserGuid() == null || application.getAttribute(requestInfo.getUserGuid()) == null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", BusinessConstants.WECHAT_STATUS.E50010003);
            map.put("msg", "登陆权限已经过期");
            resInfo.setResult(map);
            return resInfo;
        }
        SessionVo sessionVo = (SessionVo) application.getAttribute(requestInfo.getUserGuid());
        List<UserAddress> userAddressList = userAddressService.findByUserId(sessionVo.getUserId());
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        //用户收货信息列表
        for (UserAddress userAddress : userAddressList) {
            Map<String, Object> map_object = new HashMap<>();
            map_object.put("addressId", userAddress.getId());//收货ID
            map_object.put("provice", userAddress.getProvinceId());//省
            map_object.put("city", userAddress.getCityId());//市
            map_object.put("area", userAddress.getAreaId());//县
            map_object.put("addressInfo", userAddress.getCompleteAddress());//详细地址
            map_object.put("phone", userAddress.getConsigneeTel());//收件人电话
            map_object.put("name", userAddress.getConsigneeName());//收货人姓名
            map_object.put("type", userAddress.getDefaultsAddress()); //默认是1, 2否
            mapList.add(map_object);
        }
        map.put("infoList", mapList);
        map.put("status", BusinessConstants.WECHAT_STATUS.SUCCESS);
        map.put("msg", "成功");
        resInfo.setResult(map);
        return resInfo;

    }


    /**
     * 修改收货地址
     *
     * @param wechatUserAddress
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/setReceiptAddress", method = RequestMethod.GET)
    @ResponseBody
    public Object getGoodlist(WechatUserAddress wechatUserAddress, HttpServletRequest request) throws Exception {
        WeChatResInfo resInfo = new WeChatResInfo();
        //根据userGuid 找到userId
        ServletContext application = request.getSession().getServletContext();
        if (application.getAttribute(wechatUserAddress.getUserGuid()) == null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", BusinessConstants.WECHAT_STATUS.E50010003);
            map.put("msg", "登陆权限已经过期");
            resInfo.setResult(map);
            return resInfo;
        }
        SessionVo sessionVo = (SessionVo) application.getAttribute(wechatUserAddress.getUserGuid());
        String userId = sessionVo.getUserId();
        Map<String, Object> map = new HashMap<>();

        String addressId = wechatUserAddress.getAddressId();
        UserAddress userAddress = null;
        if (addressId == null || "0".equals(addressId)) {
            userAddress = new UserAddress();
            userAddress.setUserId(userId);
            userAddress.setCreateTime(new Date());
            userAddress.setStatus(BusinessConstants.STATUS.NORMAL);
        } else {
            userAddress = userAddressService.findById(addressId);
            userAddress.setUpdateTime(new Date());
        }
        userAddress.setProvinceId(wechatUserAddress.getProvice());//省
        userAddress.setCityId(wechatUserAddress.getCity());//市
        userAddress.setAreaId(wechatUserAddress.getArea());//县
        userAddress.setCompleteAddress(wechatUserAddress.getAddressInfo());//详细地址
        userAddress.setConsigneeTel(wechatUserAddress.getPhone());//手机
        userAddress.setConsigneeName(wechatUserAddress.getName());//用户
        //可选，如果是第一个地址，默认为默认收件地址1、是默认收件地址 2 否
        if (wechatUserAddress.getType() == null) {
            userAddress.setDefaultsAddress(BusinessConstants.DEFAULTS_ADDRESS.NO);

        } else {
            userAddress.setDefaultsAddress(wechatUserAddress.getType());
        }
        userAddressService.saveUserAddress(userAddress);
        map.put("status", BusinessConstants.WECHAT_STATUS.SUCCESS);
        map.put("msg", "成功");
        resInfo.setResult(map);
        return resInfo;

    }


    @RequestMapping(value = "/deliveryToArea", method = RequestMethod.GET)
    @ResponseBody
    public Object getDeliveryToArea(WeChatRequest weChatRequest) {
        WeChatResInfo resInfo = new WeChatResInfo();
        String typeId = weChatRequest.getTypeId();
        Map<String, Object> map = new HashMap<>();
        if (typeId != null) {
            List<DeliveryArea> list = deliveryAreaService.findByTypeId(typeId);
            for (DeliveryArea deliveryArea : list) {
                Map<String, Object> map_object = new HashMap<>();
                map_object.put("title", deliveryArea.getTitle());
                map_object.put("imageArea", Persistence.getValue(Constants.FILEIP) + StringsToListUtil.getFistImage(deliveryArea.getImg()));//图片
                map_object.put("areaDesc", deliveryArea.getAreaDesc());
                map_object.put("busniessTime", deliveryArea.getBusniessTime());

            }
        }
        map.put("status", BusinessConstants.WECHAT_STATUS.SUCCESS);
        map.put("msg", "成功");
        resInfo.setResult(map);
        return resInfo;
    }


    @RequestMapping(value = "/deliveryInformation", method = RequestMethod.GET)
    @ResponseBody
    public Object getDeliveryInformation(WeChatRequest weChatRequest, HttpServletRequest request) {
        WeChatResInfo resInfo = new WeChatResInfo();
        //根据userGuid 找到userId
        ServletContext application = request.getSession().getServletContext();
        if (application.getAttribute(weChatRequest.getUserGuid()) == null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", BusinessConstants.WECHAT_STATUS.E50010003);
            map.put("msg", "登陆权限已经过期");
            resInfo.setResult(map);
            return resInfo;
        }
       /* SessionVo sessionVo = (SessionVo) application.getAttribute(weChatRequest.getUserGuid());
        String userId = sessionVo.getUserId();*/
        String orderId = weChatRequest.getOrderId();
        Order order = orderService.findById(orderId);
        if (order == null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", BusinessConstants.WECHAT_STATUS.E50010003);
            map.put("msg", "订单号不存在");
            resInfo.setResult(map);
            return resInfo;
        }
        if (StringUtil.isEmpty(order.getStreamType())) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", BusinessConstants.WECHAT_STATUS.E50010003);
            map.put("msg", "快递公司代码不存在");
            resInfo.setResult(map);
            return resInfo;

        }
        if (StringUtil.isEmpty(order.getTrackingNo())) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", BusinessConstants.WECHAT_STATUS.E50010003);
            map.put("msg", "快递单号不存在");
            resInfo.setResult(map);
        }
        Integer expressStatus = order.getExpressStatus();
        List<Express> list = null;
        if (expressStatus < BusinessConstants.EXPRESS_STATUS.DELIVERY) {
            //判断查询时间间隔
            //第三方获取时间

            ExpressResponse response = ExpressUtil.getExpressResponse(order.getStreamType(), order.getTrackingNo());
            if (!"0".equals(response.getShowapi_res_code())) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("status", response.getShowapi_res_code());
                map.put("msg", response.getShowapi_res_error());
                resInfo.setResult(map);
                return resInfo;
            }
            if (response.getShowapi_res_body() != null) {
                if (!"0".equals(response.getShowapi_res_body().getRet_code())) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("status",response.getShowapi_res_body().getRet_code());
                    map.put("msg","物流接口调用失败");
                    resInfo.setResult(map);
                    return resInfo;
                }
                Integer currenStatus = response.getShowapi_res_body().getStatus();//当前快递状态
                if(BusinessConstants.EXPRESS_STATUS.QUERY_EXCEPTION.equals(currenStatus)) {
                     Map<String, Object> map = new HashMap<String, Object>();
                    map.put("status",-1);
                    map.put("msg","查询异常");
                    resInfo.setResult(map);
                    return resInfo;
                } else if(BusinessConstants.EXPRESS_STATUS.NO_RECORD.equals(currenStatus)) {
                     Map<String, Object> map = new HashMap<String, Object>();
                    map.put("status",1);
                    map.put("msg","暂无记录");
                    resInfo.setResult(map);
                    return resInfo;
                }else if(BusinessConstants.EXPRESS_STATUS.INVALID_SINGLE.equals(currenStatus)) {
                     Map<String, Object> map = new HashMap<String, Object>();
                    map.put("status",7);
                    map.put("msg","无效单");
                    resInfo.setResult(map);
                    return resInfo;
                }

                List<ExpreeResData> data = response.getShowapi_res_body().getData();

                if (currenStatus > BusinessConstants.EXPRESS_STATUS.ON_THE_WAY) {

                }
            }
        } else {
            list = expressService.findAllByOrderId(order.getId());
        }
        Map<String, Object> map = new HashMap<>();
        List<Map> mapList = new ArrayList<Map>();
        for (Express express : list) {
            Map<String, Object> map_object = new HashMap<>();
            map_object.put("time", express.getTime());
            map_object.put("addressInfo", express.getContent());//描述信息
            mapList.add(map_object);
        }
        map.put("deliveryList", mapList);
        map.put("status", BusinessConstants.WECHAT_STATUS.SUCCESS);
        map.put("msg", "成功");

        return null;
    }


}
